/*
 * 
 * 
 * 
 */
package com.hboxs.asl.controller.asl.product;

import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.Message;
import com.hboxs.asl.controller.asl.BaseController;
import com.hboxs.asl.entity.*;
import com.hboxs.asl.service.*;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Controller - 购物车
 */
@Controller("aslCartController")
@RequestMapping("/weChat/cart")
public class CartController extends BaseController {

    protected Logger logger = Logger.getLogger(getClass().getName());

    @Resource(name = "cartItemServiceImpl")
    private CartItemService cartItemService;
    @Resource(name = "promotionServiceImpl")
    private PromotionService promotionService;
    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "receiverServiceImpl")
    private ReceiverService receiverService;
    @Resource(name = "cartServiceImpl")
    private CartService cartService;
    @Resource(name = "productServiceImpl")
    private ProductService productService;


    /**
     * 添加购物车项
     *
     * @param productId
     * @param quantity
     * @param anchorId  主播id
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public
    @ResponseBody
    Object add(Long productId, Integer quantity, Long anchorId) {
        try {
            synchronized (String.valueOf(memberService.getCurrent().getId()).intern()) {
                if (quantity == null || quantity < 1) {
                    return JsonMessage.error("商品数量必须为正整数");
                }
                Product product = productService.find(productId);
                if (product == null) {
                    return JsonMessage.error("找不到该商品");
                }
                if (!product.getIsMarketable()) {
                    return JsonMessage.error("该商品已下架");
                }

                Cart cart = cartService.getCurrent(memberService.getCurrent());
                if (Cart.MAX_PRODUCT_COUNT != null && cart.getCartItems().size() >= Cart.MAX_PRODUCT_COUNT) {
                    return JsonMessage.error("最多允许添加" + Cart.MAX_PRODUCT_COUNT + "种商品至购物车");
                }

                if (cart.contains(product)) {
                    CartItem cartItem = cart.getCartItem(product);
                    if (CartItem.MAX_QUANTITY != null && cartItem.getQuantity() + quantity > CartItem.MAX_QUANTITY) {
                        return JsonMessage.error("商品数量不允许超过" + CartItem.MAX_QUANTITY);
                    }
                    if (product.getStock() != null && cartItem.getQuantity() + quantity > product.getAvailableStock()) {
                        return JsonMessage.error("该商品库存不足");
                    }
                    cartItemService.add(cartItem, quantity);
                } else {
                    if (CartItem.MAX_QUANTITY != null && quantity > CartItem.MAX_QUANTITY) {
                        return JsonMessage.error("商品数量不允许超过" + CartItem.MAX_QUANTITY);
                    }
                    if (product.getStock() != null && quantity > product.getAvailableStock()) {
                        return JsonMessage.error("该商品库存不足!");
                    }
                    cartItemService.create(product, quantity, cart, null, anchorId);
                }
                return JsonMessage.success(
                        "msg", "添加成功",
                        "count", cartService.getTotalNumberOfGoodsInCart(cart));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 立即购买
     *
     * @param productId 商品id
     * @param quantity  商品数量
     * @param anchorId  主播id
     * @return json
     */
    @RequestMapping(value = "/buy_now", method = RequestMethod.POST)
    public
    @ResponseBody
    Object buy_now(Long productId, Integer quantity, Long anchorId) {
        try {
            Product product = productService.find(productId);
            if (product == null) {
                return JsonMessage.error("找不到该商品");
            }
            Cart cart = cartService.getCurrent();

            if (cart != null) {
                if (cart.contains(product)) {
                    this.delete(cart.getCartItem(product).getId());
                }
                cartService.cancelSelected(cart);
            }
            return this.add(productId, quantity , anchorId);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }


    /**
     * 列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(ModelMap model) {
        try {
            Cart cart = cartService.getCurrent();
            cartService.dealPromotion(cart);
            // 推荐促销
            if (cart != null) {
                List<Promotion> ps = promotionService.findListNotInCart(cart);
                model.addAttribute("promotions", ps);
            }
            model.addAttribute("cart" , cart);
            model.addAttribute("count", cartService.getTotalNumberOfGoodsInCart(cart));
            if(cart!=null){
                model.addAttribute("splitCartItems",  cartService.splitCart(cart));
            }
            return "/yijing/cart";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 促销推荐商品列表
     */
    @RequestMapping(value = "/promotion-products", method = RequestMethod.GET)
    public String promotionProducts(Long promotionId, ModelMap model, HttpSession session) {
        try {
            Promotion promotion = promotionService.find(promotionId);
            if (promotion == null) {
                return "redirect:list.htm";
            }
            Cart cart = cartService.getCurrent();
            if (cart != null) {
                Set<Product> products = promotionService.findProductByPromotion(promotion, cart);
                model.addAttribute("products", products);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/yijing/product-list-promotion";
    }

    /**
     * 编辑
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public
    @ResponseBody
    Map<String, Object> edit(Long id, Integer quantity) {
        Map<String, Object> data = new HashMap<String, Object>();
        if (quantity == null || quantity < 1) {
            data.put("message", ERROR_MESSAGE);
            return data;
        }
        Cart cart = cartService.getCurrent();
        if (cart == null || cart.isEmpty()) {
            data.put("message", Message.error("shop.cart.notEmpty"));
            return data;
        }
        CartItem cartItem = cartItemService.find(id);
        Set<CartItem> cartItems = cart.getCartItems();
        if (cartItem == null || cartItems == null || !cartItems.contains(cartItem)) {
            data.put("message", Message.error("shop.cart.cartItemNotExsit"));
            return data;
        }
        if (CartItem.MAX_QUANTITY != null && quantity > CartItem.MAX_QUANTITY) {
            data.put("message", Message.warn("shop.cart.maxCartItemQuantity", CartItem.MAX_QUANTITY));
            return data;
        }
        Product product = cartItem.getProduct();
        if (product.getStock() != null && quantity > product.getAvailableStock()) {
            data.put("message", Message.warn("shop.cart.productLowStock"));
            return data;
        }
        cartItem.setQuantity(quantity);
        cartItemService.update(cartItem);
        data.put("count", cartService.getTotalNumberOfGoodsInCart(cart));
        data.put("message", SUCCESS_MESSAGE);
        data.put("subtotal", cartItem.getSubtotal());
        data.put("isLowStock", cartItem.getIsLowStock());
        data.put("quantity", cart.getQuantity());
        data.put("effectivePoint", cart.getEffectivePoint());
        data.put("effectivePrice", cart.getEffectivePrice());
        data.put("weight", cart.getWeight());
        return data;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public
    @ResponseBody
    Map<String, Object> delete(Long id) {
        Map<String, Object> data = new HashMap<String, Object>();
        Cart cart = cartService.getCurrent();
        if (cart == null || cart.isEmpty()) {
            data.put("message", Message.error("shop.cart.notEmpty"));
            return data;
        }
        CartItem cartItem = cartItemService.find(id);
        Set<CartItem> cartItems = cart.getCartItems();
        if (cartItem == null || cartItems == null || !cartItems.contains(cartItem)) {
            data.put("message", Message.error("shop.cart.cartItemNotExsit"));
            return data;
        }
        cartItems.remove(cartItem);
        cartItemService.delete(cartItem);

        data.put("message", SUCCESS_MESSAGE);
        data.put("quantity", cart.getQuantity());
        data.put("effectivePoint", cart.getEffectivePoint());
        data.put("effectivePrice", cart.getEffectivePrice());
        data.put("isLowStock", cart.getIsLowStock());
        return data;
    }

    /**
     * 清空
     */
    @RequestMapping(value = "/clear", method = RequestMethod.POST)
    public
    @ResponseBody
    Message clear() {
        Cart cart = cartService.getCurrent();
        cartService.delete(cart);
        return SUCCESS_MESSAGE;
    }


    /**
     * 修改购物车选择标记
     */
    @RequestMapping(value = "/selected", method = RequestMethod.POST)
    public
    @ResponseBody
    Object changeSelectedStatus(Long cartItemId, Boolean isSelected) {
        try {
            CartItem cartItem = cartItemService.find(cartItemId);
            if (cartItem == null && isSelected == null) {
                return JsonMessage.error("购物项参数错误");
            }
            cartItemService.changeSelectedStatus(cartItem, isSelected);
            return JsonMessage.success(
                    JsonMessage.optimiseObj(cartService.getCurrent(),
                            "effectivePrice")
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

}